﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace XrmLibrary.ConfigFile
{
    [ConfigurationCollection(typeof(AdapterInstance), CollectionType=ConfigurationElementCollectionType.AddRemoveClearMap)]
    public class AdapterInstanceCollection : ConfigurationElementCollection
    {
        private static ConfigurationPropertyCollection _properties;

        #region Constructors
        static AdapterInstanceCollection()
        {
            _properties = new ConfigurationPropertyCollection();
        }

        public AdapterInstanceCollection()
        {}
        #endregion

        #region Properties
        protected override ConfigurationPropertyCollection Properties
        {
            get { return _properties; }
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
        }

        #endregion


        #region Indexers
        public AdapterInstance this[Int32 index]
        {
            get { return (AdapterInstance)base.BaseGet(index); }
            set
            {
                if(base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                base.BaseAdd(index, value);
            }
        }


        public AdapterInstance this[String name]
        {
            get { return (AdapterInstance) base.BaseGet(name); }
        }
        #endregion


        protected override ConfigurationElement CreateNewElement()
        {
            return new AdapterInstance();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return (element as AdapterInstance).Key;
        }

        protected override bool OnDeserializeUnrecognizedAttribute(string name, string value)
        {
            if(name == InstanceName)
            {
                this.Name = value;
                return true;
            }
            return base.OnDeserializeUnrecognizedAttribute(name, value);
        }

        private const String InstanceName = "name";
        [ConfigurationProperty(InstanceName, DefaultValue = "", IsKey = false, IsRequired = false)]
        public String Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        private String _name;

    }
}
